import axios from 'axios';
import Constants from 'expo-constants';

// 自定义错误接口
interface CustomError extends Error {
  response?: {
    data: {
      message?: string;
      code?: number;
    }
  }
}

// 创建axios实例
const api = axios.create({
  baseURL: (Constants.expoConfig?.extra?.API_URL as string) || 'http://192.168.20.81:8101', // 通过环境变量配置API地址，兜底默认值
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
  withCredentials: true, // 支持跨域请求携带cookie
});

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    // 如果状态码为0，表示请求成功
    if (response.data.code === 0) {
      return response.data;
    }
    // 如果状态码不是0，创建一个错误对象，包含服务器返回的错误信息
    const error = new Error(response.data.message || '请求失败') as CustomError;
    error.response = {
      data: {
        message: response.data.message,
        code: response.data.code
      }
    };
    return Promise.reject(error);
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 用户相关API
export const userApi = {
  // 用户登录
  login(params: { studentId: string; userPassword: string }) {
    return api.post('/api/user/login', params);
  },

  // 用户注册
  register(params: { 
    studentId: string; 
    userPassword: string; 
    checkPassword: string;
    email?: string;
    phone?: string;
  }) {
    return api.post('/api/user/register', params);
  },
  
  // 用户注销
  logout() {
    return api.post('/api/user/logout');
  },

  // 获取当前登录用户信息
  getCurrentUser() {
    return api.get('/api/user/get/login');
  },

  // 更新个人信息
  updateUserInfo(params: { 
    userName?: string; 
    userAvatar?: string;
    userProfile?: string;
    nickname?: string;
    gender?: string;
    grade?: string;
    college?: string;
    major?: string;
    researchDirection?: string;
    email?: string;
    phone?: string;
    qq?: string;
    wechat?: string;
    skills?: string;
  }) {
    return api.post('/api/user/update/my', params);
  },

  // 上传用户头像
  uploadAvatar(file: FormData) {
    return api.post('/api/user/update/avatar', file, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
  },

  // 获取当前登录用户统计数据
  getUserStats() {
    return api.get('/api/user/stats');
  },

  // 获取粉丝列表
  getFollowers(params: { current?: number; pageSize?: number } = {}) {
    return api.get('/api/user/followers', { params });
  },
  
  // 获取关注列表
  getFollowings(params: { current?: number; pageSize?: number } = {}) {
    return api.get('/api/user/followings', { params });
  },
  
  // 关注/取消关注用户
  toggleFollowUser(followedUserId: number) {
    return api.post(`/api/user/follow/${followedUserId}`);
  },
  
  // 检查是否已关注用户
  checkIsFollowing(followedUserId: number) {
    return api.get(`/api/user/follow/check/${followedUserId}`);
  },
  
  // 获取用户关注数量
  getFollowingCount(userId: number) {
    return api.get(`/api/user/follow/count/following/${userId}`);
  },
  
  // 获取用户粉丝数量
  getFollowersCount(userId: number) {
    return api.get(`/api/user/follow/count/followers/${userId}`);
  }
};

// 导出updateUserInfo函数，方便直接引用
export const updateUserInfo = userApi.updateUserInfo;
export const uploadAvatar = userApi.uploadAvatar;
export const getUserStats = userApi.getUserStats;
export const getFollowers = userApi.getFollowers;
export const getFollowings = userApi.getFollowings;
export const toggleFollowUser = userApi.toggleFollowUser;
export const checkIsFollowing = userApi.checkIsFollowing;
export const getFollowingCount = userApi.getFollowingCount;
export const getFollowersCount = userApi.getFollowersCount;

export default api; 